package com.ls.rbac.security;

/**
 * created by liush on 2025/6/27
 **/

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomAnonymousEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        AuthenticationResult authenticationResult = new AuthenticationResult(null, HttpStatus.UNAUTHORIZED.value(), "匿名用户禁止访问", null, null);
        String jsonString = JSON.toJSONString(authenticationResult);
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.close();
    }
}
